package cn.com.cfae.iras.doc.analyze.components.consistency;

import cn.com.cfae.iras.doc.analyze.beans.consistency.InvestorProtectionClause;
import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.model.CatalogModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.PageModel;
import cn.com.cfae.iras.doc.analyze.service.consistencyregulation.ConsistencyRegulationService;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PageMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by zouxun on 2018/10/29
 */
@Component("U1013")
@Scope("prototype")
public class U1013 extends BaseComponent {
    private static Logger logger = LoggerFactory.getLogger(U1013.class);

    @Autowired
    U1004 u1004;
    @Autowired
    ConsistencyRegulationService consistencyRegulationService;

    /**
     *
     * @desc 设立“投资人保护条款数据库”，统计所有过会出通道项目添加投资人保护条款的情况，以企业和出通道时间为指针，在下次该企业新注册项目时，提供之前该企业投保条款添加详情。
     * @return
     *
     */
    @Override
    public List<ComponentResult> handlerM() {
        logger.info("开始调用U1013组件,处理M表...............");
        Map<String,String[]> catalogMap = new HashMap<>();
        String[] fxrmcCatalog = new String[]{"M-3","M-0","M-5","M-13"};
        String[] zwrzgjmcCatalog = new String[]{"M-0","M-3"};
        catalogMap.put("fxrmc",fxrmcCatalog);
        catalogMap.put("zwrzgjmc",zwrzgjmcCatalog);
        List<ComponentResult> componentResults = ruleCheck(catalogMap);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        logger.info("开始调用U1013组件,处理BM表...............");
        Map<String,String[]> catalogMap = new HashMap<>();
        String[] fxrmcCatalog = new String[]{"BM-3","BM-0","BM-5","BM-13"};
        String[] zwrzgjmcCatalog = new String[]{"BM-0","BM-3"};
        catalogMap.put("fxrmc",fxrmcCatalog);
        catalogMap.put("zwrzgjmc",zwrzgjmcCatalog);
        List<ComponentResult> componentResults = ruleCheck(catalogMap);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        logger.info("开始调用U1013组件,处理DM表................");
        Map<String,String[]> catalogMap = new HashMap<>();
        String[] fxrmcCatalog = new String[]{"DM-3","DM-0","DM-5","DM-13"};
        String[] zwrzgjmcCatalog = new String[]{"DM-0","DM-3"};
        catalogMap.put("fxrmc",fxrmcCatalog);
        catalogMap.put("zwrzgjmc",zwrzgjmcCatalog);
        List<ComponentResult> componentResults = ruleCheck(catalogMap);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        logger.info("开始调用U1013组件,处理BDM表................");
        Map<String,String[]> catalogMap = new HashMap<>();
        String[] fxrmcCatalog = new String[]{"BDM-3","BDM-0","BDM-5","BDM-13"};
        String[] zwrzgjmcCatalog = new String[]{"BDM-0","BDM-3"};
        catalogMap.put("fxrmc",fxrmcCatalog);
        catalogMap.put("zwrzgjmc",zwrzgjmcCatalog);
        List<ComponentResult> componentResults = ruleCheck(catalogMap);
        return componentResults;
    }


    private String getChapterData(List<PageModel> pageModelList){
        StringBuilder stringBuilder = new StringBuilder();
        if(CollectionUtils.isNotEmpty(pageModelList)){
            for(PageModel pageModel:pageModelList){
                JsonArray jsonTextDataArray = pageModel.getJsonTextData()!=null?pageModel.getJsonTextData().getAsJsonArray():null;
                if(jsonTextDataArray!=null){
                    for(JsonElement element : jsonTextDataArray){
                        JsonArray dataArray = element.getAsJsonObject()!=null?element.getAsJsonObject().getAsJsonArray("data"):null;//当页文本
                        if(dataArray!=null){
                            for (int i = 0; i < dataArray.size(); i++) {
                                JsonArray e = dataArray.get(i).getAsJsonArray();
                                for (int y = 0; y < e.size(); y++) {
                                    JsonObject data = e.get(y).getAsJsonObject();
                                    if(data!=null){
                                        String text = data.get("text").getAsJsonPrimitive().getAsString();
                                        stringBuilder.append(text);
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
        return stringBuilder.toString();
    }


    private String getText(String[] catalogArray,String modelName,String itemName){
        DocumentModel documentModel = super.getExtractData();
        for(String catalog:catalogArray){
            ChapterModel chapterModel = documentModel.getChapterModel(catalog);
            if(chapterModel!=null){
                KVText kvTextValue = getKVTextValue(catalog,modelName,itemName);
                if(kvTextValue!=null){
                    String text = kvTextValue.getText();
                    if(StringUtils.isNotEmpty(text)){
                        logger.info("章节：{}，获取数据：{}",catalog,text);
                        return text;
                    }
                }
            }
        }
        return null;
    }

    private List<ComponentResult> ruleCheck(Map<String,String[]> catalogMap){
        DocumentModel documentModel = super.getExtractData();

        List<ComponentResult> componentResults = new ArrayList<>();

        ComponentResult componentResult = u1004.getComponentResult(getCatalogId(),getCatalogId(),getRuleTitle(),"投资人保护条款","",true,getRegulationId(),0,null,"03");

        String[] keywordArray = new String[]{"交叉保护条款","事先承诺条款","事先约束条款","控制权变更条款","偿债保障承诺条款","资产抵押条款","资产质押条款"};

        ChapterModel chapterModel = documentModel.getChapterModel(getCatalogId());

        try{
            if(chapterModel!=null){
                componentResult.setPageNum(chapterModel.getStartPage());

                List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();

                List<PageModel> pageModelList = chapterModel.getPageModelList();

                boolean existFlag = false;

                if(CollectionUtils.isNotEmpty(pageModelList)){
                    top:for(PageModel pageModel:pageModelList){
                        JsonArray jsonTextDataArray = pageModel.getJsonTextData()!=null?pageModel.getJsonTextData().getAsJsonArray():null;
                        if(jsonTextDataArray!=null){
                            for(JsonElement element : jsonTextDataArray){
                                JsonArray dataArray = element.getAsJsonObject()!=null?element.getAsJsonObject().getAsJsonArray("data"):null;//当页文本
                                if(dataArray!=null){
                                    for (int i = 0; i < dataArray.size(); i++) {
                                        JsonArray e = dataArray.get(i).getAsJsonArray();
                                        for (int y = 0; y < e.size(); y++) {
                                            JsonObject data = e.get(y).getAsJsonObject();
                                            String text = data.get("text").getAsJsonPrimitive().getAsString();
                                            Double top = data.get("top").getAsJsonPrimitive().getAsDouble();
                                            Double left = data.get("left").getAsJsonPrimitive().getAsDouble();
                                            for(String keyword:keywordArray){
                                                if(text.contains(keyword)){
                                                    logger.info("M-11包含投保条款，第{}行数据，内容：{}", i, text);
                                                    ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                                                    textPosition.setContent(text);
                                                    textPosition.setX(left);
                                                    textPosition.setY(top);
                                                    textPositionList.add(textPosition);
                                                    componentResult.setPageNum(pageModel.getPageNumber());
                                                    componentResult.setTextPosition(textPositionList);
                                                    componentResult.setAnnotationFlag(false);
                                                    existFlag = true;
                                                    break top;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                String[] fxrmcArr = catalogMap.get("fxrmc");
                String[] zwrzgjmcArr = catalogMap.get("zwrzgjmc");

                String fxrmc = getText(fxrmcArr,"FXR","FXRMC");//发行人名称
                logger.info("发行人名称：{}",fxrmc);
                String zwrzgjmc = getText(zwrzgjmcArr,"FXTK","ZWRZGJMC");//债务融资工具名称
                logger.info("债务融资工具名称：{}",zwrzgjmc);

                if(existFlag){
                    String m11ChapterData=getChapterData(pageModelList);

                    if(StringUtils.isNotEmpty(m11ChapterData)){
                        if(StringUtils.isNotEmpty(fxrmc)){
                            InvestorProtectionClause investorProtectionClause = new InvestorProtectionClause();

//                        fxrmc=fxrmc.replaceAll("\\s{0,}(。)s{0,}","");
                            fxrmc=fxrmc.replaceAll("\\s{1,}","");
                            logger.info("发行人名称，格式处理：{}",fxrmc);

                            if(StringUtils.isNotEmpty(zwrzgjmc)){
                                zwrzgjmc = zwrzgjmc.replaceAll("\\s{1,}","");
                                logger.info("债务融资工具名称，格式处理：{}",zwrzgjmc);
                                investorProtectionClause.setProjectName(zwrzgjmc);
                            }

                            //删除历史数据
                            Map params = new HashMap();
                            params.put("issuer",fxrmc);
                            consistencyRegulationService.deleteInsuranceClause(params);

                            investorProtectionClause.setClauseId(UUID.randomUUID().toString());
                            investorProtectionClause.setIssuer(fxrmc);
                            investorProtectionClause.setInsuranceClause(m11ChapterData);
                            investorProtectionClause.setCheckTime(new Timestamp(System.currentTimeMillis()));
                            //写入新数据
                            consistencyRegulationService.addInsuranceClause(investorProtectionClause);

                            componentResult.setExist("01");
                            componentResult.setAnnotationFlag(false);
                            componentResult.setPromptMessage("已入库");
                        }
                    }else{
                        componentResult.setPromptMessage("未识别数据");
                        componentResult.setAnnotationFlag(false);
                        componentResult.setExist("03");
                    }
                }else{
                    componentResult.setPromptMessage("缺失");
                    componentResult.setExist("02");
                }
            }else{
                componentResult.setPromptMessage("未识别".concat(getCatalogId()).concat("数据"));
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            if(StringUtils.isNotEmpty(componentResult.getPromptMessage())){
                componentResult.setPromptMessage("未识别数据");
            }
            if(componentResult.getPageNum()==0){
                if(chapterModel!=null){
                    componentResult.setPageNum(chapterModel.getStartPage());
                }
            }
        }

        componentResults.add(componentResult);
        return componentResults;
    }
}
